#pragma once
#include <algorithm>
#include <jsoncpp/json/json.h>
#include "index.hpp"

namespace yjz_searcher
{
    class Searcher
    {
    public:
        Searcher(){}
        ~Searcher(){}

        struct InvertedElemPrint
        {
            uint64_t doc_id;
            int weight;
            std::vector<std::string> words; // 多个词对应同一个doc_id
            InvertedElemPrint() : doc_id(0), weight(0) {}
        };

        void InitSearcher(const std::string &input)
        {
            // 获取或创建index对象
            _index = yjz_index::Index::GetInstance();
            std::cout << "获取或创建index单例成功！" << std::endl;
            _index->BuildIndex(input);
            std::cout << "建立正排和倒排索引成功！" << std::endl;
        }

        void Search(const std::string &query, std::string *json_string)
        {
            // 1.分词，对query(搜索关键字)按要求进行分词
            std::vector<std::string> words;
            yjz_util::JiebaUtil::CutString(query, &words);

            // 2.触发，根据分好的词进行索引查找，关键字需要忽略大小写
            // yjz_index::Index::InvertedList inverted_list_all;

            std::unordered_map<uint64_t, InvertedElemPrint> tokens_map; // 通过doc_id去重

            for (auto word : words)
            {
                boost::to_lower(word);
                yjz_index::Index::InvertedList *inverted_list = _index->GetInvertedList(word);
                if (inverted_list == nullptr) continue;
                //inverted_list_all.insert(inverted_list_all.end(), inverted_list->begin(), inverted_list->end());
                for (const auto &elem : *inverted_list)
                {
                    auto &item = tokens_map[elem.doc_id]; // 根据doc_id找到相同的索引节点
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight; // 权重累加
                    item.words.push_back(elem.word); // 将相同doc_id的关键词管理到一起
                }
            }

            std::vector<InvertedElemPrint> inverted_list_all; // 保存不重复的倒排拉链节点
            for (const auto &item : tokens_map)
            {
                inverted_list_all.push_back(std::move(item.second));
            }

            // 3.合并排序，汇总查找结果，按照权重排降序
            // std::sort(inverted_list_all.begin(), inverted_list_all.end(), 
            //     [](const yjz_index::InvertedElem& e1, const yjz_index::InvertedElem& e2){
            //         return e1.weight > e2.weight;
            //     });
            std::sort(inverted_list_all.begin(), inverted_list_all.end(), 
                [](const InvertedElemPrint &e1, const InvertedElemPrint &e2){
                    return e1.weight > e2.weight;
                });

            // 4.根据查找出来的结果，构建Json串
            Json::Value root;
            for (auto &it : inverted_list_all)
            {
                // 根据文档ID进行正排索引
                yjz_index::DocInfo *doc = _index->GetForwardIndex(it.doc_id); 
                if (doc == nullptr) continue;
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content, it.words[0]);
                elem["url"] = doc->url;

                // for Debug
                // elem["id"] = it.doc_id;
                // elem["weight"] = it.weight;
                root.append(elem);
            }

            // Json::StyledWriter writer;
            Json::FastWriter writer;
            *json_string = writer.write(root);
        }

        // 获取摘要
        std::string GetDesc(const std::string &html_content, const std::string &word)
        {
            const int pre_step = 50;
            const int next_step = 100;

            // 找到首次出现
            auto it = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), [](char x, char y){
                return std::tolower(x) == std::tolower(y);
            });
            if (it == html_content.end()) return "None1";
            int pos = std::distance(html_content.begin(), it);

            int start = 0;
            int end = html_content.size() - 1;
            start = std::max(start, pos - pre_step);
            end = std::min(end, pos + next_step);
            if (start >= end) return "None2";
            return html_content.substr(start, end - start);
        }
    private:
        yjz_index::Index *_index; 
    };
}